import type { App, Directive, DirectiveBinding } from "vue";

/**
 *  v-draggable
 *  v-draggable="class" // 如果class存在,则移动的是class,否则移动的是当前层
 *  拖拽指令
 */

interface ElType extends HTMLElement {
  parentNode: any;
}
const mounted = (el: ElType, binding: DirectiveBinding) => {
  el.style.cursor = "move";
  const elClass = binding.value;
  let dom = el;

  if (typeof elClass === "function") {
    const classDom = elClass();
    if (classDom) {
      dom = classDom.value;
    }
  } else if (typeof elClass === "string") {
    const classDom = document.getElementsByClassName(elClass)[0] as any;
    if (classDom) {
      dom = classDom;
    }
  }

  el.onmousedown = function (e) {
    let disX = e.pageX - dom.offsetLeft; // 鼠标按下位置 -  层左边距 得出鼠标在层的位置
    let disY = e.pageY - dom.offsetTop;
    document.onmousemove = function (e) {
      let x = e.pageX - disX; // 鼠标按下位置 - 鼠标在层的位置，得出左边距离
      let y = e.pageY - disY;
      let maxX =
        parseInt(window.getComputedStyle(dom.parentNode).width) -
        parseInt(window.getComputedStyle(dom).width);
      let maxY =
        parseInt(window.getComputedStyle(dom.parentNode).height) -
        parseInt(window.getComputedStyle(dom).height);
      console.log(maxY + dom.clientHeight);
      maxY = maxY + dom.clientHeight - 80;
      // if (x < 0) {
      //  // x = 0;
      // } else if (x > maxX) {
      //   x = maxX;
      // }

      if (y < 0) {
        y = 0;
      } else if (y > maxY) {
        y = maxY;
      }
      dom.style.left = x + "px";
      dom.style.top = y + "px";
    };
    document.onmouseup = function () {
      document.onmousemove = document.onmouseup = null;
    };
  };
};

const draggable: Directive = {
  mounted,
};
const nodraggable: Directive = {
  mounted: (el: ElType, binding: DirectiveBinding) => {
    el.style.cursor = "default";
    el.onmousedown = function (e) {
      e.stopPropagation();
    };
  },
};
export const setupDraggableDirective = (app: App<Element>) => {
  app.directive("draggable", draggable);
  app.directive("nodraggable", nodraggable);
};
export default draggable;
